package main

import (
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"github.com/tidwall/gjson"
	"hash/crc32"
	"io/ioutil"
	cassandra "mycassandra"
	"net/http"
	"strconv"
	"time"
)

/**
* Router
*
* app_id   应用AID，如：lamp
* owner_id 所属ID，如：用户pkId、手机号
* type_id  类型ID，如：路灯上报、显示器上报
* msg      消息内容，支持JSON
* sign     签名
*
* @author Moks
*/
func setupRouter() *gin.Engine {

	r := gin.Default()

	// Send by body of json
	r.POST("/send", func(c *gin.Context) {

		// Parameters
		defer c.Request.Body.Close()
		body, _  := ioutil.ReadAll(c.Request.Body)
		bodyJSON := string(body)
		appId    := gjson.Get(bodyJSON, "app_id").String()
		ownerId  := gjson.Get(bodyJSON, "owner_id").String()
		typeId   := gjson.Get(bodyJSON, "type_id").String()
		msg      := gjson.Get(bodyJSON, "msg").String()
		sign     := gjson.Get(bodyJSON, "sign").String()

		// current time
		currentTime := time.Now()

		// Call Insert
		go cassandra.Insert(appId,ownerId,typeId,msg,currentTime,sign)

		// Return result
		c.String(http.StatusOK, "{\"status\":\"OK\"}")
	})

	// Send by body(msg) + rest
	r.POST("/send/:app_id/:owner_Id/:type_id/:sign", func(c *gin.Context) {

		// Parameters
		defer c.Request.Body.Close()
		body, _  := ioutil.ReadAll(c.Request.Body)
		msg      := string(body)

		appId   := c.Param("app_id")
		ownerId := c.Param("owner_Id")
		typeId  := c.Param("type_id")
		sign    := c.Param("sign")

		// current time
		currentTime := time.Now()


		// Call Insert
		go cassandra.Insert(appId,ownerId,typeId,msg,currentTime,sign)

		// Return result
		c.String(http.StatusOK, "{\"status\":\"OK\"}")
	})


	// Search by parameter of rest
	r.POST("/search/:app_id/:quantity/:action", func(c *gin.Context) {

		// Parameters
		appId       := c.Param("app_id")
		quantity    := c.Param("quantity")
		action      := c.Param("action")

		var quantityInt,_ = strconv.Atoi(quantity)

		// Call Search
		var	searchData = cassandra.Search(appId,quantityInt,action)

		// Return result
		c.String(http.StatusOK, searchData)
	})

	return r
}



/**
* Digital uuid
* struct:
* uuid: time.UnixNano()[19 bits] + hashCode(uuid)[9-10 bits]
*
* Date: 2019-10-30
* Author: Moks
 */
func GenUUID(currentTime time.Time) string{

	timestamp  := currentTime.UnixNano()
	uuid,_     := uuid.NewV4()
	uuidHash   := int64(crc32.ChecksumIEEE([]byte(uuid.String())))
	if -uuidHash >= 0 {
		uuidHash =  -uuidHash
	}

	duid := strconv.FormatInt(timestamp,10)
	return duid
}


// Listen in 9001
func main() {
	// Product model
	gin.SetMode(gin.ReleaseMode)

	// Router
	r := setupRouter()
	r.Run(":9001")
}
